package com.calendar.backend;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.widget.PopupWindow;
import android.widget.Toast;

public class Events extends Activity {

	/**
	 * Returns a list of calendars on this phone.  Information includes
	 * the calendar's name and ID.
	 * 
	 * @return	Vector containing information about the calendars on this phone.
	 */
	public Vector<CalendarInfo> getCalendars(Context context) {
		
		String[] projection = { "_id", "displayName" };
		Uri calendarsUri = Uri.parse("content://com.android.calendar/calendars");
		     
		Cursor calendarCursor = context.getContentResolver().query(calendarsUri, projection, null, null, null);
		
		String calName = "";
		String calID = "";
		Vector<CalendarInfo> calendars = null;
		
		if(calendarCursor != null && calendarCursor.getCount() > 0) {
			
			calendarCursor.moveToFirst();
			calendars = new Vector<CalendarInfo>();
			
			int nameColumn = calendarCursor.getColumnIndex("displayname"); 
			int idColumn = calendarCursor.getColumnIndex("_id");

			do {
				
				calName = calendarCursor.getString(nameColumn);
				calID = calendarCursor.getString(idColumn);
				
				calendars.add(new CalendarInfo(calName, calID));
		    
			} while(calendarCursor.moveToNext());
			
		} else {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			
			builder.setMessage("No active calendars detected!");
			builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                Events.this.finish();
		           }
		       });
			
			builder.create();
		}
		
		calendarCursor.close();
		return calendars;
	}
	
	/**
	 * Returns a list of the events occurring between the given times.
	 * 
	 * @param start	Beginning of the range, in milliseconds.
	 * @param end	End of the range, in milliseconds.
	 * @return		Vector containing all events occurring between the given times.
	 */
	public Vector<Event> findEvents(Context context, long start, long end) {
		
		Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
        ContentUris.appendId(builder, start);
        ContentUris.appendId(builder, end);
		
        String contentProvider;
        if(android.os.Build.VERSION.SDK_INT > 7)
    		contentProvider = "com.android.calendar";
        else
    		contentProvider = "calendar";
        Uri eventsUri = Uri.parse(String.format("content://%s/events",contentProvider));

//        Cursor eventCursor = context.getContentResolver().query(eventsUri,null,"dtstart BETWEEN "+start+" AND " + end + " OR dtend BETWEEN " + start + " AND " + end ,null,null);
//		Cursor eventCursor = context.getContentResolver().query(builder.build(), new String[] {"title", "begin", "end"}, "Calendars._id=?", new String[] { id }, null);
		Cursor eventCursor = context.getContentResolver().query(builder.build(), null, null, null, null);
		Vector<Event> events = new Vector<Event>();
		
		if(eventCursor != null && eventCursor.getCount() > 0) {
			
			eventCursor.moveToFirst();
			
			do {
				
				String eventID = "";
				String calID = "";
				String title = "";
				String description = "";
				String location = "";
				long startTime = 0;	//	In milliseconds
				long endTime = 0;	//	In milliseconds
				long duration = 0;
				boolean allDay = false;
				boolean alarm = false;
				int color = 0;

				for(int i = 0; i < eventCursor.getColumnCount(); i++) {
					
//					if(eventCursor.getString(i) != null)
//						Log.e("Col", eventCursor.getColumnName(i) + " = " + eventCursor.getString(i) );
//					
//					else
//						Log.e("Col", eventCursor.getColumnName(i) + " = ");
//					
					if( eventCursor.getColumnName(i).equals("event_id")) {

						eventID = eventCursor.getString(i);
						
					} else if(eventCursor.getColumnName(i).equals("calendar_id")) {
						
						calID = eventCursor.getString(i);
						
					} else if(eventCursor.getColumnName(i).equals("title")) {
						
						title = eventCursor.getString(i);
						
					} else if(eventCursor.getColumnName(i).equals("description")) {
						
						description = eventCursor.getString(i);
						
					} else if(eventCursor.getColumnName(i).equals("eventLocation")) {
						
						location = eventCursor.getString(i);
						
					} else if(eventCursor.getColumnName(i).equals("dtstart")) {
						
						startTime = Long.parseLong(eventCursor.getString(i));
						
					} else if(eventCursor.getColumnName(i).equals("dtend")) {
						
						if(eventCursor.getString(i) != null) {
							endTime = Long.parseLong(eventCursor.getString(i)); 
						} else {
//							Calendar cal = Calendar.getInstance();
//							cal.setTime(new Date( end));
//							cal.set(Calendar.HOUR_OF_DAY, 22);
//							endTime = cal.getTimeInMillis();
						}
					} else if(eventCursor.getColumnName(i).equals("duration")) {
						
						String temp = eventCursor.getString(i);
						
						if( temp != null && !temp.equals("")) {
							
							//	Should start with 'P'... Don't know why....
							temp = temp.substring(1);
							
							//	If the last char is a 'S', unit is in seconds.
							if(temp.charAt(temp.length() - 1) == 'S') {
								
								temp = temp.substring(0, temp.length() - 1);
								duration = Long.parseLong(temp) * 1000;
								
							}
							//	If the last char is a 'D', unit is in days.
							else if(temp.charAt(temp.length() - 1) == 'D') {
								
								temp = temp.substring(0, temp.length() - 1);
								duration = Long.parseLong(temp) * 1000 * 86400;
							}
						}
						
					} else if(eventCursor.getColumnName(i).equals("allDay")) {
						
						if(eventCursor.getString(i).equals("1"))
							allDay = true;
						
						else
							allDay = false;
						
					} else if(eventCursor.getColumnName(i).equals("hasAlarm")) {
						
						if(eventCursor.getString(i).equals("1"))
							alarm = true;
						
						else
							alarm = false;
						
					} else if(eventCursor.getColumnName(i).equals("color")) {
						
						color = Integer.parseInt(eventCursor.getString(i));
					}
				}
				
				if(endTime == 0)
				{
					endTime = startTime + duration;
				}
				
				if(true == allDay) {
					
					//	Adjust for the time zone change.
					TimeZone tz = TimeZone.getDefault();
					startTime -= tz.getRawOffset();
					endTime -= tz.getRawOffset();
					
					//	Verify the event still occurs within our range...
					if((start < startTime && startTime < end) || (start < endTime && endTime < end)) 	{
					
						events.add(new Event(false, context, eventID, calID, title, description, location,
								startTime, endTime, allDay, alarm, color));
						
					}
				} else {
					
					events.add(new Event(false, context, eventID, calID, title, description, location,
							startTime, endTime, allDay, alarm, color));
					
				}
				
			} while(eventCursor.moveToNext());
			
			eventCursor.close();
		}
		
		return events;
	}
}
